package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Goods;
import com.ywgt.pojo.GoodsAllinone;
import com.ywgt.service.GoodsService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/admin/goods")
@ApiModel("商品管理")
public class GoodsController {

    @Autowired
    GoodsService goodsService;

    /**
     *   page: 1,
     *         limit: 20,
     *         goodsSn: undefined,
     *         name: undefined,
     *         sort: 'add_time',
     *         order: 'desc'
     * @return
     */
    @GetMapping("/list")
    public Object getGoods(String name,String goodsSn,@RequestParam(required = false,defaultValue = "add_time") String sort,
                           @RequestParam(required = false,defaultValue = "desc") String order,
                           @RequestParam(required = false,defaultValue = "1") int page,
                           @RequestParam(required = false,defaultValue = "10") int limit){
        Page<Goods> goods=goodsService.getGoods(name,goodsSn,page,limit,sort,order);
        List<Goods> items = goods.getResult().stream().filter(g ->!g.getDeleted()).collect(Collectors.toList());
        long total = goods.getTotal();
        Map<String,Object> data=new HashMap<>();
        data.put("total",total);
        data.put("items",items);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@RequestBody GoodsAllinone goodsAllinone){
        return goodsService.create(goodsAllinone);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody Goods goods){
        if(goodsService.removeById(goods.getId())){
            return ResponseUtil.ok();
        }
        return ResponseUtil.fail();
    }
    @PostMapping("/update")
    public Object update(@RequestBody GoodsAllinone goodsAllinone){
        return goodsService.updateGoods(goodsAllinone);
    }

    @GetMapping("/catAndBrand")
    public Object catAndBrand(){
        return goodsService.catAndBrand();
    }

    @GetMapping("/detail")
    public Object detail(Integer id){
        return goodsService.detail(id);
    }
}
